Encapsulation

  • Note

    Encapsulation is a process in which data and action bind together.

    In encapsulation, the variables of a class are not accessible from outside the class. These variables can access only by the methods in which declared in the same class. It is also known as data hiding.

    Why Encapsulation?

    Better control of class attributes and methods

    Flexible: the programmer can change one part of the code without affecting other parts

    Increased security of data

    Advatages

    1. It gives better maintainability and flexibility and re-usability

    If you are changing in variable name or value, then other classes will not affect this change. They can still simply access the setter and getter. We can it at any point in time. This is introducing maintained property because we can change it without breaking classes.

    2. Data Hiding:

    By use of encapsulation, we can achieve data hiding. It hides the implementation detail of the class from the outside user. The user only knows how to pass the value to the setter and how to get the value from the getter. There is nothing too visible to the user about how the class is storing values in the variables.

    3. Access Control:

    By using access modifiers (like public, private, and protected), encapsulation enables you to control the visibility of members (attributes and methods) within a class. Public methods provide a controlled way to interact with an object's state.

    4. Security:

    Encapsulation helps in improving security by restricting access to certain parts of an object. Critical data can be kept private, and only authorized methods can modify or access that data.

    5. Facilitates Testing and Debugging:

    Encapsulation makes it easier to test and debug code because each class is a self-contained unit. Changes to one class are less likely to impact other parts of the system, making it easier to isolate and fix issues.

    When to use encapsulation

    If any programmer is manipulating those fields directly, it may break the consistency of those fields. The programmer may change only one field without changing important related fields. But instead of this, we can make a method that will communicate to interdependent fields. If the programmer wants to change the field, he just needs to call a method and the method will update all fields.